/**
 * 详情对话框
 */
layui.use(['form', 'admin', 'ax','laydate','upload','formSelects','upload','element'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var upload = layui.upload;
    var element  = layui.element ;


    //获取详情信息，填充表单
    var ajax = new $ax(Feng.ctxPath + "/workOrderShenpi/detail?id=" + Feng.getUrlParam("id"));
    var result = ajax.start();
    form.val('btyCwJsForm', result.data);

    // 上传食品经营许可证
    var imgsp = $('#pic').val();
    $(function (){
        if (imgsp != ''){
            $('#uploader-list-sp').append('<img style="width: 80px;height: 80px;" src="'+ imgsp +'"  class="layui-upload-imgsp" onclick="imgViewersp(this)">')
        }
    })

    var tempView = null
    imgViewersp = function (img) {
        tempView = $('.layui-upload-imgsp')
        tempView.viewer()
        return
    };
    $('#uploader-list-sp1').click(function (){
        $('#uploader-list-sp1').viewer()
    })

    var arr;
    var uploadInst = upload.render({
        elem: '#sp_upload_btn'
        ,accept: 'images'
        ,auto: false
        ,url: '/btySzgl/uploadImg' //此处用的是第三方的 http 请求演示，实际使用时改成您自己的上传接口即可。
        ,before: function(obj){
            //预读本地文件示例，不支持ie8
            obj.preview(function(index, file, result){
                $('#uploader-list-sp1').attr('src', result); //图片链接（base64）
            });

            element.progress('demo', '0%'); //进度条复位
            layer.msg('上传中', {icon: 16, time: 0});
        }   // 图片压缩
        , choose: function (obj) { //选择文件后的回调
            var files = obj.pushFile();
            var filesArry = [];
            for (var key in files) { //将上传的文件转为数组形式
                filesArry.push(files[key])
            }
            var index = filesArry.length - 1;
            var file = filesArry[index]; //获取最后选择的图片,即处理多选情况

            if (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion.split(";")[1]
                .replace(/[ ]/g, "").replace("MSIE", "")) < 9) {
                return obj.upload(index, file)
            }
            canvasDataURL(file, function (blob) {
                var aafile = new File([blob], file.name, {
                    type: file.type
                });
                var isLt1M;
                if (file.size < aafile.size) {
                    isLt1M = file.size
                } else {
                    isLt1M = aafile.size
                }
                if (isLt1M / 1024 / 1024 > 2) {
                    return layer.alert('上传图片过大！')
                } else {
                    if (file.size < aafile.size) {
                        return obj.upload(index, file)
                    }
                    obj.upload(index, aafile)
                }
            })
        }
        ,done: function(res){
            //如果上传失败
            if(res.code > 0){
                return layer.msg('上传失败');
            }
            //上传成功的一些操作
            //……
            $('#demoSp').html(''); //置空上传失败的状态
            //上传完毕
            // arr.push(res.data.src);
            arr = res.data.src;
            $("#pic").val(arr);
        }
        ,error: function(){
            //演示失败状态，并实现重传
            var demoSp = $('#demoSp');
            demoSp.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoSp.find('.demo-reload').on('click', function(){
                uploadInst.upload();
            });
        }
        //进度条
        ,progress: function(n, elem, e){
            // element.progress('demo', n + '%'); //可配合 layui 进度条元素使用
            if(n == 100){
                layer.msg('上传完毕', {icon: 1});
                $(".layui-upload-imgsp").css("display","none")
            }
        }
    });

    // 图片压缩
    function canvasDataURL(file, callback) { //压缩转化为base64
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function (e) {
            const img = new Image();
            const quality = 0.2 // 图像质量比例
            const canvas = document.createElement('canvas');
            const drawer = canvas.getContext('2d');
            img.src = this.result;
            img.onload = function () {
                canvas.width = img.width;
                canvas.height = img.height;
                drawer.drawImage(img, 0, 0, canvas.width, canvas.height);
                convertBase64UrlToBlob(canvas.toDataURL(file.type, quality), callback);
            }
        }
    }

    function convertBase64UrlToBlob(urlData, callback) { //将base64转化为文件格式
        const arr = urlData.split(',');
        const mime = arr[0].match(/:(.*?);/)[1];
        const bstr = atob(arr[1]);
        let n = bstr.length;
        const u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        callback(new Blob([u8arr], {
            type: mime
        }));
    }




    //表单提交事件
    form.on('submit(btnSubmit)', function (data) {
        var ajax = new $ax(Feng.ctxPath + "/workOrderShenpi/editItem", function (data) {
            Feng.success("更新成功！");

            //传给上个页面，刷新table用
            admin.putTempData('formOk', true);

            //关掉对话框
            admin.closeThisDialog();

        }, function (data) {
            Feng.error("更新失败！" + data.responseJSON.message)
        });
        ajax.set(data.field);
        ajax.start();

        return false;
    });

});